<?php
/**
 * Created by PhpStorm.
 * User: XIE XIN
 * Date: 2017/10/19
 * Time: 13:58
 */

namespace App\Repositories;

use App\Models\Student;
use App\Models\TeachingAssessment;
use App\Models\TeachingCourseware;
use App\Models\TeachingCurriculum;
use App\Models\TeachingExchange;
use App\Models\TeachingPay;
use App\Models\TeachingSet;
use App\Models\TeachingSimulate;
use App\Models\TeachingStudyPace;
use App\Models\TeachingType;
use App\Models\TeachingWatch;
use App\Models\TeachingWrong;
use ClassesWithParents\F;
use function GuzzleHttp\Promise\exception_for;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class TeachingRepository extends BaseRepository
{
    protected $exchange;
    protected $courseware;
    protected $curriculum;
    protected $pay;
    protected $assessment;
    protected $studyPace;
    protected $teachingType;
    protected $wrong;

    public function __construct(
        TeachingExchange $teachingExchange,
        TeachingCourseware $teachingCourseware, //课件
        TeachingCurriculum $teachingCurriculum, //课程
        TeachingPay $teachingPay,
        TeachingAssessment $teachingAssessment,
        TeachingStudyPace $teachingStudyPace,
        TeachingSimulate $teachingSimulate,
        TeachingType $teachingType,
        TeachingWrong $teachingWrong
    )
    {
        $this->exchange = $teachingExchange;
        $this->courseware = $teachingCourseware;
        $this->curriculum = $teachingCurriculum;
        $this->pay = $teachingPay;
        $this->assessment = $teachingAssessment;
        $this->studyPace = $teachingStudyPace;
        $this->model = $teachingSimulate;
        $this->teachingType = $teachingType;
        $this->wrong = $teachingWrong;
    }

    /**
     * 问答列表
     * @param $param
     * @param string $id
     * @param $size
     * @return mixed
     * @author zengxiangyu
     */
    public function exchangeList($param, $id = '', $size)
    {
        if ($id) {
            $list = $this->exchange->where('type', 1)
                ->where('user_id', $id)
                ->select('id', 'user_id', 'text', 'type', 'created_at')
                ->limit($size)
                ->offset(($param['page'] - 1) * $size)
                ->orderBy('id', 'desc')
                ->get();
        } else {
            $list = $this->exchange->where('type', '1')
                ->select('teaching_exchange.id', 'teaching_exchange.user_id', 'teaching_exchange.text', 'teaching_exchange.type',
                    'teaching_exchange.created_at', 'students.name', 'students.photo')
                ->join('students', 'students.id', '=', 'teaching_exchange.user_id')
                ->limit($size)
                ->offset(($param['page'] - 1) * $size)
                ->orderBy('teaching_exchange.id', 'desc')
                ->get();
        }
        foreach ($list as $v) {
            $count = $this->exchange->where('exchange_id', $v->id)->count();
            $v->count = $count;
        }
        return $list;
    }

    /**
     * 问答详情列表
     * @param $id
     * @param $item
     * @return array
     * @author zengxiangyu
     */
    public function exchangeDetail($id, $item)
    {
        $data = $this->exchange->where('teaching_exchange.id', $id)
            ->select('teaching_exchange.id', 'teaching_exchange.user_id', 'teaching_exchange.type', 'teaching_exchange.text',
                'teaching_exchange.created_at', 'students.name', 'students.photo')
            ->join('students', 'students.id', '=', 'teaching_exchange.user_id')
            ->first();

        $list = $this->exchange->where('teaching_exchange.exchange_id', $id)
            ->select('teaching_exchange.id', 'teaching_exchange.user_id', 'teaching_exchange.type', 'teaching_exchange.text',
                'teaching_exchange.created_at', 'students.name', 'students.photo')
            ->join('students', 'students.id', '=', 'teaching_exchange.user_id')
            ->orderBy('id', 'desc')
            ->get();

        $rs['info'] = $data;
        $rs['list'] = $list;

        return $rs;
    }

    /**
     * 理论学习列表
     * @param $param
     * @param $size
     * @param string $item
     * @return mixed
     * @author zengxiangyu
     */
    public function curriculumList($param, $size, $item = '')
    {
        $data = $this->curriculum->where(['teaching_curriculum.km' => $param['km'], 'teaching_curriculum.status' => 1])
            ->where('teaching_curriculum.train_type', 'like', '%' . $item->traintype . '%')
            ->where('teaching_curriculum.study_at', '>=', date('Y-m-d', time()))
            ->join('teaching_type', 'teaching_type.id', '=', 'teaching_curriculum.courseware_pid')
            ->select('teaching_curriculum.id', 'teaching_curriculum.name', 'teaching_curriculum.courseware_id', 'teaching_curriculum.study_time',
                'teaching_curriculum.type', 'teaching_curriculum.access', 'teaching_curriculum.money')
            ->limit($size)
            ->offset(($param['page'] - 1) * $size)
            ->orderBy('teaching_type.sort', 'asc')
            ->get();
        return $data;
    }


    /**
     * 课件展示
     * @param $id
     * @param $item
     * @param $size
     * @param $page
     * @return mixed
     * @author zengxiangyu
     */
    public function coursewareList($id, $item, $size, $page)
    {
        $ids = $this->curriculum->where('id', $id)->value('courseware_id');
        //todo评论 (连表
        $ids = explode(',', $ids);
        $data = $this->courseware->where(['teaching_courseware.status' => 1])
            ->where('teaching_courseware.train_type', 'like', '%' . $item->traintype . '%')
//            ->leftjoin('teaching_study_pace as study', 'study.courseware_id', '=', 'teaching_courseware.id')
//            ->leftjoin('teaching_assessment as assessment', 'assessment.courseware_id', '=', 'teaching_courseware.id')
//            ->leftjoin('teaching_watch as watch', 'watch.courseware_id', '=', 'teaching_courseware.id')
//            ->join('students', 'students.id', '=', 'watch.user_id')
            ->whereIn('teaching_courseware.id', $ids)
            ->select('teaching_courseware.id', 'teaching_courseware.name', 'teaching_courseware.url', 'teaching_courseware.courseware_time',
                'teaching_courseware.type', 'teaching_courseware.access', 'teaching_courseware.money')
            ->limit($size)
            ->offset(($page - 1) * $size)
            ->get();
        foreach ($data as $v) {
            $isWatch = TeachingWatch::where(['user_id' => $item->id, 'courseware_id' => $v->id])->value('is_watch');
            $studyPace = TeachingStudyPace::where(['user_id' => $item->id, 'courseware_id' => $v->id])->first();
            $assId = TeachingAssessment::where(['user_id' => $item->id, 'courseware_id' => $v->id])->value('id');;
            if ($studyPace) {
                $v->study_pace = $studyPace->study_pace ? $studyPace->study_pace : null;
                $v->second = $studyPace->second ? $studyPace->second : null;
            } else {
                $v->study_pace =  null;
                $v->second = null;
            }
            $v->assessment_id = $assId ? $assId : null;
            $v->is_watch = $isWatch ? $isWatch : null;
        }
        return $data;
    }

    /**
     * 查询用户是否购买课程
     * @param $id
     * @param $item
     * @return mixed
     * @author zengxiangyu
     */
    public function isPay($id, $item)
    {
        $rs = false;
        $type = $this->curriculum->where('id', $id)->value('type');
        if ($type == 2) {
            $rs = $this->pay->where(['user_id' => $item->id, 'curriculum_id' => $id])->value('is_pay');
        }
        return $rs;
    }

    /**
     * 查看课件评论
     * @param $id
     * @author zengxiangyu
     */
    public function assessment($id)
    {
        $rs = $this->assessment->where('id', $id)
            ->select('id', 'assessment_content', 'assessment_method', 'assessment_result', 'service_attitude',
                'service_capacity', 'service_efficiency', 'text')
            ->first();

        $data = [
          'id' => $rs->id,
          'assessment_content' => $rs->assessment_content,
          'assessment_method' => $rs->assessment_method,
          'assessment_result' => $rs->assessment_result,
          'service_attitude' => $rs->service_attitude,
          'service_capacity' => $rs->service_capacity,
          'service_efficiency' => $rs->service_efficiency,
          'text' => $rs->text,
        ];
        return $data;
    }

    /**
     * 课件评论
     * @param $data
     * @param $item
     * @return mixed
     * @author zengxiangyu
     */
    public function assessmentAdd($data, $item)
    {
        $data['user_id'] = $item->id;
        $data['stunum'] = $item->stunum;
        $data['school_id'] = $item->school_id;
        $data['assessment_time'] = date('Y-m-d H-i-s', time());
        $data['created_at'] = time();
        $data['updated_at'] = time();
        $rs = $this->assessment->insert($data);
        return $rs;
    }

    /**
     * 学习进度更新
     * @param $data
     * @param $item
     * @return mixed
     * @author zengxiangyu
     */
    public function studyPaceUpdate($data, $item)
    {
        $data['user_id'] = $item->id;
        $data['updated_at'] = time();
        //计算进度
        $courseware_time = $this->courseware->where('id', $data['courseware_id'])->value('courseware_time');
        //换算秒
        $courseware_second = $courseware_time * 60;
        if ($courseware_second <= $data['second']) {
            $data['study_pace'] = 100;
        } else {
             $data['study_pace'] =round(($data['second']/$courseware_second)*100,2);
        }
        $res = $this->studyPace->where(['courseware_id' => $data['courseware_id'], 'user_id' => $item->id])->value('id');
        if ($res) {
            $rs = $this->studyPace->where('id', $res)->update($data);
        } else {
            $data['created_at'] = time();
            $rs = $this->studyPace->insert($data);
        }
        return $rs;
    }

    /**
     * 获取考试试题
     * @param $km
     * @param $item
     * @return array
     * @author zengxiangyu
     */
    public function getSimulate($km, $item)
    {
        //如果是科目一，练习试题比例为  判断题40 单选题60
        if ($km == 1) {
            $tm_judge = 40;
            $tm_single = 60;
            $tm_multiple = 0;

            //如果是科目四，练习题比例为   判断22  单选22  多选6
        } elseif ($km == 4) {
            $tm_judge = 22;
            $tm_single = 22;
            $tm_multiple = 6;
        } else {
            return [];
        }

        //随机获取单选题
        $single = $this->getSimulateID([['km', $km], ['type', '1']], $tm_single, $item);

        //随机获取多选题
        $multiple = $this->getSimulateID([['km', $km], ['type', '2']], $tm_multiple, $item);

        //随机获取判断题
        $judge = $this->getSimulateID([['km', $km], ['type', '3']], $tm_judge, $item);

        $simulate_data = array_merge($single, $multiple, $judge);
        //打乱题目
        shuffle($simulate_data);
        if ($simulate_data) {
            $data['question'] = $this->model->find($simulate_data[0]['id']);
            if ($data['question']['url']) {
                if (!strpos($data['question']['url'],'http')) {
                    $data['question']['url'] = 'http://www.exc360.com'.$data['question']['url'];
                }
            }
            $data['question']['answer'] = explode('||', $data['question']['answer']);
            $data['simulate'] = $simulate_data;
        } else {
            $data = [];
        }
        return $data;

    }

    /**
     * 获取题目ID
     * @param $where
     * @param $limit
     * @param $item
     * @return array
     * @author zengxiangyu
     */
    public function getSimulateID($where, $limit, $item)
    {
        $where[] = ['status', '1'];
        $simulate_ids = $this->model->select('id')->where($where)
            ->where('train_type', 'like', '%' . $item->traintype . '%')
            ->limit($limit)
            ->inRandomOrder()
            ->get()
            ->toArray();

        $data = [];
        if ($simulate_ids) {
            return $simulate_ids;
        }
        return $data;
    }

    /**
     * 获取科目的章节列表
     * @param $data
     * @param $item
     * @return mixed
     * @author zengxiangyu
     */
    public function getChapterList($data, $item)
    {
        $chapterList = $this->teachingType
            ->where(['km' => $data['km'], 'depth' => 3, 'type' => 1])
            ->select('id', 'name', 'km')
            ->get()
            ->toArray();

        return $chapterList;
    }

    /**
     * 章节列表题目
     * @param $data
     * @return array
     * @author zengxiangyu
     */
    public function getChapterLearn($data)
    {
        $teachingType = $this->teachingType->where('pid', $data['pid'])->get();
        $ids = [];
        foreach ($teachingType as $k => $v) {
            $ids[$k] = $v->id;
        }

        $chapter_list = $this->model
            ->whereIn('teaching_type', $ids)
            ->limit(1)
            ->offset($data['page'] - 1)
            ->get()
            ->toArray();

        $count = $this->model->whereIn('teaching_type', $ids)->count();
        if ($chapter_list) {
            foreach ($chapter_list as $k => $chapter) {
                $chapter_list[$k]['answer'] = explode('||', $chapter['answer']);
                if ($chapter_list[$k]['url']) {
                    if (!strpos($chapter_list[$k]['url'], 'http')) {
                        $chapter_list[$k]['url'] = 'http://www.exc360.com' . $chapter_list[$k]['url'];
                    }
                }
            }
        }
        return ['list' => $chapter_list, 'count' => $count];
    }

    /**
     * 章节练习(顺序 随机)
     * @param $data
     * @param $item
     * @return array
     * @author zengxiangyu
     */
    public function learnList($data, $item)
    {
        $chapter_list = $this->model
            ->where([['km', $data['km']]])
            ->where('train_type', 'like', '%' . $item->traintype . '%')
            ->limit(1)
            ->offset($data['page'] - 1);

        if ($data['order_type'] == 1) {
            $chapter_list = $chapter_list->orderBy('id')->get()->toArray();
        } else {
            $chapter_list = $chapter_list->inRandomOrder()->get()->toArray();
        }

        $count = $this->model
            ->where([['km', $data['km']]])
            ->where('train_type', 'like', '%' . $item->traintype . '%')
            ->count();

        if ($chapter_list) {

            foreach ($chapter_list as $k => $chapter) {
                $chapter_list[$k]['answer'] = explode('||', $chapter['answer']);
                if ($chapter_list[$k]['url']) {
                    if (!strpos($chapter_list[$k]['url'], 'http')) {
                        $chapter_list[$k]['url'] = 'http://www.exc360.com' . $chapter_list[$k]['url'];
                    }
                }
            }

        }
        return ['list' => $chapter_list, 'count' => $count];
    }

    /**
     * 错误列表
     * @param $km
     * @param $item
     * @return array
     * @author zengxiangyu
     */
    public function getWrongList($km, $item)
    {
        $wrongList = $this->wrong->select('simulate_id')
            ->where(['user_id' => $item->id, 'km' => $km])
            ->get()
            ->toArray();

        $data = [];
        if ($wrongList) {
            $data['question'] = $this->model->find($wrongList[0]['simulate_id']);
            $data['question']['answer'] = explode('||', $data['question']['answer']);
            if ($data['question']['url']) {
                if (!strpos($data['question']['url'],'http')) {
                    $data['question']['url'] = 'http://www.exc360.com'.$data['question']['url'];
                }
            }
            $data['simulate'] = $wrongList;
        }
        return $data;
    }

    /**
     * @param $data
     * @param $item
     * @return mixed
     * @author zengxiangyu
     */
    public function wrongUpdate($data, $item)
    {
        $data['user_id'] = $item->id;
        $data['updated_at'] = time();
        $simulate_id = $this->wrong->where(['simulate_id' => $data['simulate_id'], 'user_id' => $item->id])->value('simulate_id');

        if (!empty($data['is_delete'])) {
            $rs = $this->wrong->where('simulate_id', $data['simulate_id'])->delete();
        } elseif ($simulate_id) {
            return true;
        } else {
            unset($data['is_delete']);
            $data['created_at'] = time();
            $rs = $this->wrong->insert($data);
        }
        return $rs;
    }

    /**
     * 更新视频记录
     * @param $inputs
     * @param string $extra
     * @return bool
     * @author zengxiangyu
     */
    public function theoryRecord($inputs, $extra = '')
    {
        //视频学习记录-
//        $id = $this->model->insertGetId($inputs);
        //学时培训记录
        $time = time();
        $putime_log = $inputs;
        $putime_log['endtime'] = $time;
        $putime_log['startime'] = $time - $inputs['duration']; //满足以前的畸形命名
        $putime_log['photo1'] = 'http://image.stjp360.com/teaching_photo/'.$inputs['student_id'].'_'.$inputs['courseware_id'].'_1.jpg';
        $putime_log['photo2'] = 'http://image.stjp360.com/teaching_photo/'.$inputs['student_id'].'_'.$inputs['courseware_id'].'_2.jpg';
        $putime_log['date'] = $time;
        $putime_log['sign'] = strtoupper(md5($time.'klbHLNnokLIHlHILHhl'));
        $putime_log['is_watch'] = 1;//视频学习
//        $putime_log['video_learn_id'] = $id;

        $ch = curl_init(env('THEROY_POST_URL'));

        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $putime_log);
        $body = curl_exec($ch);

        $tmp = json_decode($body, true);
        return true;
    }

    /**
     * 查询教学设置
     * @return array
     * @author zengxiangyu
     */
    public function getSet()
    {
        $data = [
          'idcard_time' => TeachingSet::where('id', 1)->value('idcard_time'),
          'interaction_time' => TeachingSet::where('id', 1)->value('interaction_time')
        ];
        return $data;
    }

    /**
     * 资源列表
     * @param  array $data 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function index($data = [], $extra = '', $size = '10')
    {
        $list = '';

        return $list;
    }

    /**
     * IRepository接口store方法
     * 请在子类中重写或重载具体的实现方法
     * @param  array $inputs
     * @param  string|array $extra
     * @return void
     */
    public function store($inputs, $extra = '')
    {
        $model = new $this->model;
        return $this->save($model, $inputs, true);

    }

    public function insert($text, $item, $type = 1, $exchange_id = '')
    {
        $data = [
            'user_id' => $item->id,
            'text' => $text,
            'type' => $type,
            'created_at' => time(),
            'updated_at' => time(),
        ];

        if ($exchange_id) {
            $data['exchange_id'] = $exchange_id;
        }

        return $this->exchange->insert($data);
    }

    /**
     *  数据处理
     * @param $model
     * @param $inputs
     * @param bool $flag
     * @return mixed
     */
    public function save($model, $inputs, $flag = false)
    {
        $model->save();
        return $model;
    }

    /**更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input, $extra = '')
    {
        $model = $this->getById($id);
        $models = $this->save($model, $input);
        return $models;
    }

    /**
     * 编辑特定id资源
     *
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra = '')
    {
        return $this->getById($id);
    }
}